package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * str
 * 394. 字符串解码
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/7 14:46
 */
public class DecodeString {


    public static void main(String[] args) {
        DecodeString test = new DecodeString();

//        // aaabcbc
//        String str = "3[a]2[bc]";

        // accaccacc
//        String str = "3[a2[c]]";

//        // abcabccdcdcdef
//        String str = "2[abc]3[cd]ef";

//        // abccdcdcdxyz
//        String str = "abc3[cd]xyz";

//        // cdcdcd
        String str = "100[leetcode]";



        String string = test.decodeString(str);
        System.out.println(string);
    }

    private char[] arr;

    public String decodeString(String s) {
        arr = s.toCharArray();
        return find(0, s.length() - 1);
    }

    private String find(int st, int end) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        int item = 0;
        int a = 0;
        for (int i = st; i <= end; i++) {
            char c = arr[i];
            if (c >= '0' && c <= '9') {
                if (item == 0) {
                    count = count * 10 +  c - '0';
                }
            } else if (c == '[') {
                if (item == 0) {
                    a = i;
                }
                item++;
            } else if (c == ']') {
                item--;
                if (item == 0) {
                    String str = find(a + 1, i - 1);
                    for (int j = 0; j < count; j++) {
                        sb.append(str);
                    }
                    count = 0;
                }
            } else {
                if (item == 0) {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

}
